<?php

namespace App\HttpController\Api;

use EasySwoole\ORM\DbManager;
use App\HttpController\BaseController;
use App\Model\AppMemberModel;
use App\Model\AppFriendsModel;
use App\Model\AppMemberStoreModel;
use App\Model\MessageModel;
use App\Resources\RedisResources;
use App\Model\UserModel;
use App\Validate\UserValidate;
use App\HttpController\Api\Message;

class User extends BaseController {
    public $imgDomain = 'http://cdn.zczmer.com';

    /**
     * 用户登录
     * @description
     * @author Mr wang  2019/11/16 下午1:16
     * @return bool
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    // public function login(){
    //     $validate = (new UserValidate())->secnceName('login')->check($this->request()->getRequestParam());
    //     if ($validate !== true){
    //         $this->writeJson(0,$validate);
    //         return false;
    //     }
    //     $wechat = wechatLogin($this->request()->getRequestParam('code'));
    //     if($wechat == NULL || isset($wechat['errcode'])){
    //         $this->writeJson(0,'登录失败');
    //     }else{
    //         //查询表中是否有此值
    //         $user_info = UserModel::create()->where('open_id',$wechat['openid'])->findOne();
    //         if(empty($user_info)){
    //             $data['open_id'] = $wechat['openid'];
    //             $id = UserModel::create($data)->save();
    //         }else{
    //             $id = $user_info['id'];
    //         }
    //         if ($id === null){
    //             $this->writeJson(0,'登录失败,服务器插入错误');
    //         }else{
    //             $this->writeJson(1,'登录成功',$id);
    //         }
    //     }
    // }
    public function authLogin() {
        $post = $this->request()->getRequestParam();
        $validate = (new UserValidate())->secnceName('authLogin')->check($post);
        if ($validate !== true) {
            $this->writeJson(0, $validate);
            return false;
        }
        if (empty($post['user_id'])) {
            $this->writeJson(0, '用户id不能为空');
        }
        if (empty($post['platform_id'])) {
            $this->writeJson(0, '终端id不能为空');
        }
        $name = $post['name'] ?? '';
        //查询表中是否有此值
        if ($post['platform_id'] == 3) {
            if (empty($post['application_id'])) {
                $this->writeJson(0, '平台id不能为空');
            }
            // 聊天平台为众创织梦可以直接用member_id获取user_id
            $app_member = AppMemberModel::create()->where(['id' => $post['user_id']])->findOne();
            $name = $app_member['title'];
            $img = $this->imgDomain . $app_member['img'];
            // 商家首次进入聊天
            $app_member_store = AppMemberStoreModel::create()->where(['member_id' => $post['user_id'], 'appid' => $post['application_id'], 'store_id' => $post['store_id']])->findOne();
            if (empty($app_member_store)) {
                AppMemberStoreModel::create(['member_id' => $post['user_id'], 'appid' => $post['application_id'], 'store_id' => $post['store_id']])->save();
            }
            $user_info = UserModel::create()->where(['platform_id' => 3, 'user_id' => $post['user_id']])->findOne();
            // if($post['application_id']==3){
            //     $user_info = UserModel::create()->where(['platform_id'=>3,'user_id'=>$post['user_id'],'application_id'=>$post['application_id']])->findOne();
            // }else{
            //     $user_info = UserModel::create()->where(['platform_id'=>3,'user_id'=>$post['user_id'],'store_id'=>$post['store_id'],'application_id'=>$post['application_id']])->findOne();
            // }
        } else {
            // 聊天平台为其他时，先用appid和store_id获取member_id，再用member_id获取user_id
            $user_info = UserModel::create()->where(['platform_id' => $post['platform_id'], 'user_id' => $post['user_id']])->findOne();
        }
        // $user_info = UserModel::create()->where('platform_id',$post['platform_id'])->findOne();
        if (empty($user_info)) {
            $data['platform_id'] = $post['platform_id'];
            $data['user_id'] = $post['user_id'] ?? '';
            $data['store_id'] = $post['store_id'] ?? '';
            $data['application_id'] = $post['application_id'] ?? '';
            $data['name'] = $name;
            $data['img'] = $post['img'] ?? '';
            $data['mobile'] = $post['mobile'] ?? '';
            $data['open_id'] = $post['open_id'] ?? '';
            $data['cid'] = $post['cid'] ?? '';
            $data['lg_val'] = $post['lg_val'] ?? '';
            $id = UserModel::create($data)->save();
        } else {
            $id = $user_info['id'];

            if (!empty($post['img'])) {
                $data['img'] = $post['img'] === 'undefined' ? $img : $post['img'];
            } else if ($user_info['img'] === 'undefined' || empty($user_info['img'])) {
                $data['img'] = $img;
            }

            if (!empty($post['mobile'])) {
                $data['mobile'] = $post['mobile'];
            }
            if (!empty($post['name'])) {
                $data['name'] = $post['name'];
            } else {
                $data['name'] = $post['platform_id'] == 3 ? $name : $user_info['name'];
            }
            if (!empty($post['open_id'])) {
                $data['open_id'] = $post['open_id'];
            }

            if (!empty($post['cid'])) {
                $data['cid'] = $post['cid'];
            }
            if (!empty($post['lg_val'])) {
                $data['lg_val'] = $post['lg_val'];
            }
            if ($data) {
                UserModel::create()->update($data, ['id' => $id]);
            }
        }
        if ($id === null) {
            $this->writeJson(0, '登录失败,服务器插入错误');
        } else {
            $this->writeJson(1, '登录成功', $id);
        }
    }
    public function getStoreUid() {
        $post = $this->request()->getRequestParam();
        $userModel = UserModel::create();
        // 查询发送消息用户id
        $from_id = $userModel->where(['platform_id' => $post['application_id'], 'user_id' => $post['user_id']])->findOne();
        // 查询店铺所有uid
        $users = $userModel->alias('a')->field("a.*,b.kefu_status")->join('ty_app_member as b', 'b.id=a.user_id', 'left')->join('ty_app_member_store as c', 'c.member_id=a.user_id')->where(['a.platform_id' => $post['platform_id'], 'c.appid' => $post['application_id'], 'c.store_id' => $post['store_id'], 'b.kefu_status' => 1, 'b.app_role_id' => [5, '<>']])->select();

        // $user_info = UserModel::create()->where(['platform_id'=>$post['platform_id'],'application_id'=>$post['application_id'],'store_id'=>$post['store_id']])->findOne();
        // var_dump($userModel->lastQueryResult());
        // var_dump($users);
        if (empty($users)) {
            //该店铺没有账号登录过app
            $this->writeJson(0, '登录失败');
        } else {
            $ids = implode(',', array_column($users, 'id'));
            $where = "(send_id in ({$ids}) and from_id = {$from_id['id']}) or (send_id = {$from_id['id']} and from_id in ({$ids}))";
            $message_history = MessageModel::create()->where($where)->select();
            if (empty($message_history)) {
                //随机返回一个uid
                $this->writeJson(1, '登录成功', $users[array_rand($users, 1)]['id']);
            } else {
                //返回对话过的uid
                if ($message_history[0]['send_id'] == $from_id['id']) {
                    $this->writeJson(1, '登录成功', $message_history[0]['from_id']);
                }
                if ($message_history[0]['from_id'] == $from_id['id']) {
                    $this->writeJson(1, '登录成功', $message_history[0]['send_id']);
                }
            }
        }
    }

    public function delFriend() {
        $post = $this->request()->getRequestParam();
        $AppFriendsModel = AppFriendsModel::create();
        try {
            // 启动事务
            DbManager::getInstance()->startTransaction();
            $res1 = $AppFriendsModel->destroy(["member_id" => $post['member_id'], "friend_id" => $post['friend_id']]);
            $res2 = $AppFriendsModel->destroy(["friend_id" => $post['member_id'], "member_id" => $post['friend_id']]);
            print_r($res1);
            print_r($res2);
            if ($res1 && $res2) {
                $member = UserModel::create()->where(['user_id' => $post['member_id']])->findOne();
                $friend = UserModel::create()->where(['user_id' => $post['friend_id']])->findOne();

                $redisLink = (new RedisResources())->link();
                $redisLink->del('clist_' . $member['id']);
                $redisLink->del('clist_' . $friend['id']);
                $message = new Message();
                $message->setEmptyRedis($member['id']);
                $message->setEmptyRedis($friend['id']);
            }


            // 提交事务
            DbManager::getInstance()->commit();
            $this->writeJson(1, '删除成功');
        } catch (\Throwable $throwable) {
            // 回滚事务
            DbManager::getInstance()->rollback();
            $this->writeJson(0, '删除失败', json_encode($throwable));
        }
    }


    public function uploadImg() {
        $request = $this->request();

        // 获取一个上传文件，客户端上传的文件字段名为 'file'
        // 返回的是一个 \EasySwoole\Http\Message\UploadFile 的对象
        /** @var \EasySwoole\Http\Message\UploadFile $file */
        $file = $request->getUploadedFile('file');
        var_dump($file);
    }

    public function getUserList() {
        $userList = UserModel::create()->where('platform_id', '3', '=')->select();
        $this->writeJson(1, '用户列表', $userList);
    }

    public function userInfo() {
        $userInfo = UserModel::create()->where('id', $this->request()->getRequestParam('id'))->findOne();
        $this->writeJson(1, '用户详情', $userInfo);
    }

    public function updateInfo() {
        $params = json_decode($this->request()->getBody()->__toString(), true);
        $validate = (new UserValidate())->secnceName('update')->check($params);
        if ($validate !== true) {
            $this->writeJson(0, $validate);
            return false;
        }
        $params['name'] = $params['name'] . '_' . $params['id'];
        UserModel::create()->update($params, ['id' => $params['id']]);
    }

    /**
     * 使用redis进行用户和fd的绑定
     * @description
     * @author Mr wang  2019/11/16 下午1:35
     * @param $fd
     * @param $userId
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function userBindFd($userId, $fd, $source) {
        $redisLink = (new RedisResources())->link();
        $redisLink->set($source . '_user_' . $userId, $fd, 10800);
        print_r("绑定user" . $fd . PHP_EOL);
        print_r("绑定fd" . $userId . PHP_EOL);
        $redisLink->set('fd_' . $fd, $userId, 10800);
        $redisLink->set('source_' . $fd, $source, 10800);
    }

    /**
     * 解除绑定关系
     * @description
     * @author Mr wang  2019/11/16 下午1:43
     * @param $fd
     */
    public function userUnBindFd($fd) {
        $redisLink = (new RedisResources())->link();
        //首先根据fd获取用户id
        $userId = $redisLink->get('fd_' . $fd);
        $source = $redisLink->get('source_' . $fd);

        // $user = UserModel::create()->where("id = ".$userId)->findOne(); //清空cid
        // $data['cid'] = '';
        // UserModel::create()->update($data,['id'=>$user['id']]);
        // AppMemberModel::create()->update($data,['id'=>$user['user_id']]);

        print_r("解绑user" . $userId);

        // 如果获取到，解除绑定关系
        if (!empty($userId)) {
            $redisLink->del('fd_' . $fd);
            $redisLink->del('source_' . $fd);
            $redisLink->del($source . '_user_' . $userId);
        }
    }
}
